import json
# import uuid
import sys
import os
from revChatGPT.V1 import Chatbot
from ws4py.client.threadedclient import WebSocketClient
from ws4py.messaging import TextMessage
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
from message_forward.manger import user_manager
# from retrying import retry

user_conversation_ids = {}  # 用户会话


class CG_Client(WebSocketClient):

    
    def received_message(self, resp: TextMessage):
        respJson = json.loads(str(resp))
        user_id = respJson['user_id']
        user_query = respJson['query_msg']
        prompt = json.loads(str(user_query)).get('msg', 'hello')

        # chatbot = Chatbot(config={"access_token": accessToken})
        chatbot = Chatbot(config={
            "email": "",
            "password": ""
        })
        if  user_id in user_conversation_ids and user_conversation_ids[user_id] is not None and user_conversation_ids[user_id] != '':
            conversation_id = user_conversation_ids[user_id]
            print('已有的conversation_id：' + conversation_id)
        else:
            # str(uuid.uuid4())
            conversation_id = None
            user_conversation_ids[user_id] = conversation_id

        response = ""
        try:
            for data in chatbot.ask(prompt, conversation_id, None, 360000):
                response = data["message"]
            data = json.dumps({'msg': response})
            if conversation_id is None and data is not None:
                conversations = chatbot.get_conversations(0, 20, None)
                conversation_id = conversations[0]['id']
                print('初次获取到的conversation_id：' + conversation_id)
                user_conversation_ids[user_id] = conversation_id
                
            self.send(data)
        # except ConnectionResetError:
        #     print('********[WinError 10054] 远程主机强迫关闭了一个现有的连接。******')
        except Exception as e:
            # if user_id in user_manager:
            user_manager[user_id].close()
            user_manager.pop(user_id)
            except_type, except_value, except_traceback = sys.exc_info()
            except_file = os.path.split(except_traceback.tb_frame.f_code.co_filename)[1]
            exc_dict = {
                "报错类型": except_type,
                "报错信息": except_value,
                "报错文件": except_file,
                "报错行数": except_traceback.tb_lineno,
            }
            print(exc_dict)

def func():
    ws = None
    try:
        ws = CG_Client('ws://127.0.0.1:8020/server?token=r64XoPjdpVWPpSTrnin1')
        ws.connect()
        ws.run_forever()
    except KeyboardInterrupt:
        ws.close()

if __name__ == '__main__':
    import uvicorn
    uvicorn.run('revChatGPT2:func', host='0.0.0.0', port=8022,
                reload=True,
                reload_delay=0.25,
                ws_ping_interval=99999,
                ws_ping_timeout=99999,
                timeout_keep_alive=99999
                )
